<template>
  <!-- 暂停记录 -->
  <el-dialog
    title="暂停记录"
    class="stop-record-dialog"
    draggable
    :penetrate="true"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="807px"
    @close="closeFn"
  >
    <div class=" " style="min-height: 400px">
      <el-form
        :model="currBillType"
        :rules="currBillType.rules"
        ref="tableForm"
        label-width="0"
        :inline="true"
        size="normal"
      >
        <!-- currBillType.dataSource -->
        <el-table key="stopRecord" :data="currBillType.dataSource" height="450px" style="width: 100%">
          <el-table-column type="index" :index="indexFn" width="50" label="序号"></el-table-column>
          <el-table-column prop="witnessStopTime" label="暂停时间" min-width="200">
            <!-- witnessRecoveryTime: "2022-07-06 16:46:32"
witnessStopTime:  -->
            <template slot-scope="scope">
              <!-- {{ scope.row.witnessMinTime }} -->
              <template v-if="!scope.row.edit">
                <span :key="'STOP' + scope.row.witnessStopTime">{{ scope.row.witnessStopTime }}</span>
              </template>
              <!-- {{ scope.$index }} -->
              <el-form-item
                :key="'STOP_date' + scope.$index"
                v-if="scope.row.edit"
                label=""
                :prop="'dataSource.' + scope.$index + '.witnessStopTime'"
                :rules="currBillType.rules.witnessStopTime"
                style="margin-bottom: 0px"
              >
                <el-date-picker
                  v-if="scope.row.edit"
                  :key="'STOP_date' + scope.$index"
                  style="width: 100%"
                  v-model="scope.row.witnessStopTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期时间"
                  :picker-options="pickerOptionsFn(scope, 'STOP')"
                ></el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="witnessRecoveryTime" label="恢复时间" min-width="200">
            <template slot-scope="scope">
              <span v-if="!scope.row.edit">
                {{ scope.row.witnessRecoveryTime }}
              </span>
              <!--
                @change="witnessRecoveryTimeChangeFn" -->
              <el-form-item
                :key="'RECOVER_date' + scope.$index"
                v-if="scope.row.edit"
                label=""
                :prop="'dataSource.' + scope.$index + '.witnessRecoveryTime'"
                :rules="currBillType.rules.witnessRecoveryTime"
                style="margin-bottom: 0px"
              >
                <!-- {{ scope.$index }} -->
                <el-date-picker
                  v-if="scope.row.edit"
                  :key="'RECOVER_date' + scope.$index"
                  style="width: 100%"
                  :picker-options="pickerOptionsFn(scope, 'RECOVER')"
                  v-model="scope.row.witnessRecoveryTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="选择日期时间"
                ></el-date-picker>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="时长" min-width="150">
            <template slot-scope="scope">
              <g-timer
                :key="'' + scope.row.witnessStopTime + scope.row.witnessRecoveryTime"
                timer-type="stopRecord"
                :type="!scope.row.edit"
                :start-time="scope.row.witnessStopTime"
                :end-time="scope.row.witnessRecoveryTime"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" v-if="type !== 'read'" width="130">
            <template slot-scope="scope">
              <template v-if="scope.row.edit">
                <el-button :key="'save' + scope.$index" type="text" size="default" @click="submitUpdateFn(scope)">
                  确认
                </el-button>
                <el-button :key="'clear' + scope.$index" type="text" size="default" @click="clearEditClickFn(scope)">
                  取消
                </el-button>
              </template>
              <template v-else>
                <el-button
                  :disabled="!scope.row.witnessRecoveryTime"
                  type="text"
                  size="default"
                  @click="editRecordClickFn(scope)"
                >
                  编辑
                </el-button>
                <el-button
                  :disabled="!scope.row.witnessRecoveryTime"
                  type="text"
                  size="default"
                  @click="deleteRecordClickFn(scope)"
                >
                  删除
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <!-- <el-result v-if="activitiesNoDataFlag && !tableData.length" icon="empty1" title="暂无数据" :size="180" /> -->
      <!-- 分页 -->
      <div class="layout-footer ui-pt10">
        <!-- {{ pageObj.total + " " + pageObj.pageSize }} -->
        <pagination
          v-if="pageObj.total > pageObj.pageSizes[0] && this.pageObj.pageSize != -1"
          :total="pageObj.total"
          :page.sync="pageObj.currentPage"
          :limit.sync="pageObj.pageSize"
          :page-sizes="pageObj.pageSizes"
          @pagination="recordStopListFn"
        />
      </div>
    </div>
    <!-- <span slot="footer">
      <el-button type="primary" :loading="loading" @click="submitRecordFn">提交</el-button>
      <el-button @click="cancelFn()">取消</el-button>
    </span> -->
  </el-dialog>
</template>
<script>
  import gTimer from "../../components/timer.vue";
  import { recordStopList, recordStopUpdate, recordStopDelete } from "../../api/api";
  export default {
    name: "StopRecord",
    components: { gTimer },
    props: {
      initData: {
        type: Object,
        default() {
          return {};
        }
      },
      currData: {
        type: Object,
        default() {
          return {};
        }
      },
      topTaskActive: {
        type: String,
        default: ""
      },
      id: {
        type: String,
        default: ""
      },
      type: {
        type: String,
        default: ""
      },
      show: {
        type: Boolean,
        default: false
      }
    },
    data() {
      // eslint-disable-next-line complexity
      const msgStrFn = (rule, value, flag) => {
        // const $index = rule.field.split(".")[1];
        // const row = this.currBillType.dataSource[$index];
        // let prevDate = "";
        // let nextDate = "";
        // if (this.currBillType.dataSource[+$index - 1]) {
        //   prevDate = this.currBillType.dataSource[+$index - 1].witnessRecoveryTime;
        // }
        // if (this.currBillType.dataSource[+$index + 1]) {
        //   nextDate = this.currBillType.dataSource[+$index + 1].witnessStopTime;
        // }
        // 判断 时间范围是否正确
        let msgStr = "";
        if (!value) {
          msgStr = `${flag === "RECOVER" ? "恢复" : "暂停"}时间不能为空`;
          return msgStr;
        }
        // if (this.$moment(row.witnessStopTime) <= this.$moment(row.witnessMinTime)) {
        //   msgStr = "本次编辑的暂停时间应晚于开始见证时间，请重新输入";
        // } else if (prevDate && this.$moment(row.witnessStopTime) <= this.$moment(prevDate)) {
        //   msgStr = "本次编辑的暂停时间应晚于上一次的恢复时间，请重新输入";
        // } else if (nextDate && this.$moment(row.witnessRecoveryTime) >= this.$moment(nextDate)) {
        //   msgStr = "本次编辑的恢复时间应早于下一次的暂停时间，请重新输入";
        // } else if (
        //   row.witnessRecoveryTime &&
        //   this.$moment(row.witnessStopTime) >= this.$moment(row.witnessRecoveryTime)
        // ) {
        //   if (flag === "RECOVER") {
        //     msgStr = "本次编辑的恢复时间应晚于暂停时间，请重新输入";
        //   } else {
        //     msgStr = "本次编辑的暂停时间应早于恢复时间，请重新输入";
        //   }
        // } else if (this.$moment(row.witnessRecoveryTime) > this.$moment(Date())) {
        //   msgStr = "本次编辑的恢复时间应早于当前时间，请重新输入";
        // } else if (row.witnessMaxTime && this.$moment(row.witnessRecoveryTime) >= this.$moment(row.witnessMaxTime)) {
        //   msgStr = "本次编辑的恢复时间应早于结束时间，请重新输入";
        // }
        return msgStr;
      };
      const witnessStopTime = (rule, value, callback) => {
        console.log("rule--s", rule);
        const msgStr = msgStrFn(rule, value, "STOP");
        console.log("msgStr", msgStr);
        if (msgStr !== "") {
          return callback(new Error(msgStr));
        }
        callback();
      };
      const witnessRecoveryTime = (rule, value, callback) => {
        console.log("rule--r", rule);
        const msgStr = msgStrFn(rule, value, "RECOVER");
        console.log("msgStr", msgStr);
        if (msgStr !== "") {
          return callback(new Error(msgStr));
        }
        callback();
      };
      return {
        tableData: [],
        oldTableData: [],
        currBillType: {
          dataSource: [],
          rules: {
            witnessStopTime: [
              {
                validator: witnessStopTime,
                trigger: ["blur", "change"]
              }
            ],
            witnessRecoveryTime: [
              {
                validator: witnessRecoveryTime,
                trigger: ["blur", "change"]
              }
            ]
          }
        },
        matterInstruction: [],
        witnessMatterOptions: [],
        loading: false,
        visible: false,
        pageObj: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          pageSizes: [10, 20, 30]
        }
      };
    },
    computed: {
      // visible() {
      //   return this.show;
      // },
    },
    watch: {
      show(val) {
        this.visible = val;
        this.currBillType.dataSource = [];
        this.pageObj.total = 0;
        this.pageObj.currentPage = 1;
        this.pageObj.pageSize = 10;
        console.log("show", val);
        if (val) {
          // this.id = this.$route.query.id;
          // this.currProjectData = this.currData;
          // this.id = this.currProjectData.witnessSubTaskId;
          this.initFn();
        }
      }
    },
    methods: {
      indexFn(index) {
        return index + 1 + (this.pageObj.currentPage - 1) * this.pageObj.pageSize;
      },
      witnessRecoveryTimeChangeFn() {},
      pickerOptionsFn({ row, $index }, flag) {
        console.log("row", row);
        let obj = {};
        if (flag === "STOP") {
          let prevDate = "";
          if (this.currBillType.dataSource[$index - 1]) {
            prevDate = this.currBillType.dataSource[$index - 1].witnessRecoveryTime;
          }
          obj = {
            disabledDate(time) {
              return (
                time.getTime() > Date.now() ||
                new Date(row.witnessMinTime).getTime() - 24 * 3600 * 1000 > time.getTime() ||
                (row.witnessRecoveryTime && new Date(row.witnessRecoveryTime).getTime() < time.getTime()) ||
                (prevDate && time.getTime() < new Date(prevDate).getTime() - 24 * 3600 * 1000)
              );
            }
          };
        }
        if (flag === "RECOVER") {
          let nextDate = "";
          if (this.currBillType.dataSource[$index + 1]) {
            nextDate = this.currBillType.dataSource[$index + 1].witnessStopTime;
          }
          obj = {
            disabledDate(time) {
              return (
                time.getTime() > Date.now() ||
                (row.witnessMaxTime && new Date(row.witnessMaxTime).getTime() < time.getTime()) ||
                (row.witnessStopTime && new Date(row.witnessStopTime).getTime() - 24 * 3600 * 1000 > time.getTime()) ||
                (nextDate && time.getTime() > new Date(nextDate).getTime())
              );
            }
          };
        }
        return obj;
      },
      async initFn() {
        console.log("initFn");
        if (this.initFlag) {
          return;
        }
        this.initFlag = setTimeout(() => {
          clearTimeout(this.initFlag);
          this.initFlag = null;
        }, 300);
        this.initFromFn();
        await this.recordStopListFn();
      },
      // 见证记录-所有-添加时的禁用属性
      async recordStopListFn() {
        if (!this.id) {
          return;
        }
        const p = {
          currentPage: this.pageObj.currentPage, // 当前页数
          pageSize: this.pageObj.pageSize, // 每页条数
          witnessSubTaskId: this.id
          // pageSize: -1
        };
        this.currBillType.dataSource = [];
        console.log("this.id", this.id);
        try {
          const res = await recordStopList(p);
          if (res.success) {
            this.pageObj.total = res.data.pageBean.count;
            this.currBillType.dataSource = res.data.result;
            this.$set(this.currBillType, "dataSource", res.data.data);
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (error) {
          console.error(error);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      // 见证记录-所有-添加时的禁用属性
      submitUpdateFn({ row, $index }) {
        this.$refs["tableForm"].validate((valid) => {
          console.log("valid", valid);
          if (valid) {
            this.recordStopUpdateFn({ row, $index });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      // eslint-disable-next-line complexity
      async recordStopUpdateFn({ row, $index }) {
        let prevDate = "";
        let nextDate = "";
        if (this.currBillType.dataSource[+$index - 1]) {
          prevDate = this.currBillType.dataSource[+$index - 1].witnessRecoveryTime;
        }
        if (this.currBillType.dataSource[+$index + 1]) {
          nextDate = this.currBillType.dataSource[+$index + 1].witnessStopTime;
        }
        console.log("nextDate", nextDate);
        console.log("row.witnessRecoveryTime", row.witnessRecoveryTime);
        // 判断 时间范围是否正确
        let msgStr = "";
        if (this.$moment(row.witnessStopTime) <= this.$moment(row.witnessMinTime)) {
          if (row.afterCancelFlag === "Y") {
            msgStr = "本次编辑的暂停时间应晚于此次撤销结束见证的时间，请重新输入";
          } else {
            msgStr = "本次编辑的暂停时间应晚于开始见证时间，请重新输入";
          }
        }
        if (prevDate && this.$moment(row.witnessStopTime) <= this.$moment(prevDate)) {
          msgStr = "本次编辑的暂停时间应晚于上一次的恢复时间，请重新输入";
        }
        if (nextDate && this.$moment(row.witnessRecoveryTime) >= this.$moment(nextDate)) {
          msgStr = "本次编辑的恢复时间应早于下一次的暂停时间，请重新输入";
        }
        if (this.$moment(row.witnessStopTime) >= this.$moment(row.witnessRecoveryTime)) {
          msgStr = "本次编辑的暂停时间应早于恢复时间，请重新输入";
          // if (flag === "RECOVER") {
          //     msgStr = "本次编辑的恢复时间应晚于暂停时间，请重新输入";
          //   } else {
          //     msgStr = "本次编辑的暂停时间应早于恢复时间，请重新输入";
          //   }
        }
        if (this.$moment(row.witnessRecoveryTime) > this.$moment(Date())) {
          msgStr = "本次编辑的恢复时间应早于当前时间，请重新输入";
        }
        if (row.witnessMaxTime && this.$moment(row.witnessRecoveryTime) >= this.$moment(row.witnessMaxTime)) {
          msgStr = "本次编辑的恢复时间应早于此阶段的结束时间，请重新输入";
        }
        if (msgStr) {
          this.$message({
            type: "error",
            message: msgStr,
            single: true
          });
          return;
        }
        const p = {
          stopId: row.stopId,
          witnessStopTime: this.$moment(row.witnessStopTime).format("yyyy-MM-DD HH:mm:ss"),
          witnessRecoveryTime: this.$moment(row.witnessRecoveryTime).format("yyyy-MM-DD HH:mm:ss")
        };
        console.log("p", p);
        try {
          const res = await recordStopUpdate(p);
          if (res.success) {
            this.$message({
              type: "success",
              message: "修改成功!",
              single: true
            });
            this.$delete(row, "edit");
            // this.recordStopListFn();
            this.$emit("updateBenchFn");
          }
        } catch (error) {
          console.error(error);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      // 见证记录-所有-添加时的禁用属性
      async recordStopDeleteFn({ row, $index }) {
        const p = {
          stopId: row.stopId
        };
        // this.currBillType.dataSource = [];
        console.log("this.id", this.id);
        try {
          const res = await recordStopDelete(p);
          if (res.success) {
            this.$message({
              type: "success",
              message: "删除成功!",
              single: true
            });
            this.$delete(this.currBillType.dataSource, $index);
            // this.recordStopListFn();
            this.$emit("updateBenchFn");
          } else {
            this.$message({
              type: "error",
              message: res.message || "获取数据失败，请稍后再试",
              single: true
            });
          }
        } catch (error) {
          console.error(error);
          this.$message({
            type: "error",
            message: "获取数据失败，请稍后再试",
            single: true
          });
        }
      },
      initFromFn() {
        console.log("this.addform", this.addform);
        // this.$refs["addform"] && this.$refs["addform"].clearValidate();
        this.$refs["addform"] && this.$refs["addform"].resetFields();
      },
      // 见证事项-提交
      // async submitRecordFn(flag) {
      //   this.$refs.addform.validate((valid) => {
      //     if (valid) {
      //       this.loading = true;
      //       this.submitLoading = true;
      //       this.witnessRecordAddFn(flag);
      //     } else {
      //       console.log("error submit!!");
      //       return false;
      //     }
      //   });
      // },
      cancelFn() {
        this.visible = false;
      },
      closeFn() {
        // this.currBillType.dataSource = [];
        this.$refs["tableForm"] && this.$refs["tableForm"].clearValidate();
        this.$refs["tableForm"] && this.$refs["tableForm"].resetFields();
        this.$set(this.currBillType, "dataSource", []);
        this.$emit("close");
      },
      async submitFn() {
        this.loading = true;
        // let witnessSubTaskId = [];
        await this.subtaskReviewFn();
        this.$emit("submit");
      },
      // 提交
      submitRecordClickFn({ row }) {
        console.log("row", row);
      },
      clearEditClickFn({ row, $index }) {
        this.$delete(row, "edit");
        console.log("row", row);
        this.$set(this.currBillType.dataSource, $index, this.oldTableData[$index]);
      },
      editRecordClickFn({ row, $index }) {
        const flag = this.currBillType.dataSource.some((item) => item.edit);
        if (flag) {
          this.$message({
            type: "error",
            message: "请对正在编辑的暂停记录确认后，再进行该条记录的编辑",
            single: true
          });
          return;
        }
        this.oldRow = JSON.parse(JSON.stringify(row));
        // this.oldTableData;
        this.$set(this.oldTableData, $index, this.oldRow);
        this.$set(row, "edit", true);
        console.log("row", row);
      },
      deleteRecordClickFn({ row, $index }) {
        console.log("row", row);
        this.$confirm(`确认删除`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.recordStopDeleteFn({ row, $index });
          })
          .catch(() => {});
      }
    }
  };
</script>
<style lang="scss" scoped>
  .stop-record-dialog {
    ::v-deep .el-dialog__body {
      max-height: none;
    }
  }
</style>
